# 导入类视图
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入表
from myapp.models import User


def make_password(mypassword):
    # 生成md5对象
    md5 = hashlib.md5()
    # 转码操作
    mypass_utf8 = str(mypassword).encode(encoding='utf-8')
    # 加密操作
    md5.update(mypass_utf8)
    # 返回密文
    return md5.hexdigest()


# 注册
class Register2(APIView):
    def post(self, request):
        # 接受前端传过来的参数
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        # 去重
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 403, 'msg': '用户名已存在'})
        # 入库保存
        user = User(password=make_password(password), username=username)
        user.save()
        return Response({'code': 200, 'msg': '注册成功'})


# 登录
class Login2(APIView):
    def get(self, request):
        # 接受前端传过来的参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)
        # 与数据库数据对比
        user = User.objects.filter(username=username, password=make_password((password))).first()
        if user:
            return Response({'code': 200, 'msg': '登录成功'})
        else:
            return Response({'code': 403, 'msg': '用户名或密码错误,请重新输入'})
